function [k_out] = gen_k(eta, QQ, dates0, indUnc)
% Parameter
NQ = size(QQ,3);
%eta = (X_var' - repmat(const_var,size(X_var,1),1)'-[vec_A(1:3*lag)';vec_A(3*lag+1:6*lag)';vec_A(6*lag + 1:9*lag)']*X_exp')';
OMEGA= cov(eta);
BB0=chol(OMEGA,'lower'); %Generate lower cholesy factorization of covariance matrix eta

num_events = 2;
  dates5      = 198710; %1987/10;
% dates7012   =         %1970/12;
  dateslehman = 200809; %2008/09;


%87 crash
index_87 = [find(abs(dates0 - dates5) < 10^(-5))];

% % 1970
% index_70 = [find(abs(dates0 -dates7012)<10^(-6))];

% Lehman Crash
index_lehman = [find(abs(dates0 -dateslehman)<10^(-6)):find(abs(dates0 -dateslehman)<10^(-6))];




e_store = NaN(NQ,num_events);
for iii = 1:NQ
    
    % rotate and normalize B
    B_initial=BB0*QQ(:,:,iii);
    B_est=B_initial*diag(sign(diag(B_initial))); %normalize so that self-irfs are positive
    ehat = eta(:,:)*inv(B_est)';

    %============ Event constraint ==============
    %      Ebar(1)                 Ebar(3)             
    kkk = [ehat(index_87,indUnc)   ehat(index_lehman,indUnc)];
    
   %B_store(:,:,iii) = B_est;
    e_store(iii,:) = kkk;
end


k_out = prctile(e_store,75);
end